<?php
namespace App\Logic\Product\Form;
use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Model\Product\ProductModel;
use App\Model\UserModel;
use App\Util\UserIdentityHelper;

class ProductListForm extends BaseListForm
{
    public $id;
    public $goods_name;
    public $created_at;
    public $start_created_at;//订单创建时间 - 开始
    public $end_created_at;//订单创建时间 - 结束

    /**
     * 商品列表
     * @return \App\Core\Output
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function lists()
    {
        $where = [];
        if (UserIdentityHelper::getType() == UserModel::TYPE_INSIDE) {
            /**后台管理员*/
        } else {
            throw new DefaultException('权限不足');
            $this->user_id    = UserIdentityHelper::getId();
            $where['user_id'] = $this->user_id;
        }

        if ($this->checkField($this->id)) {
            $where['id'] = $this->id;
        }
        if ($this->checkField($this->goods_name)) {
            $where['goods_name'] = $this->goods_name;
        }
        if ($this->checkField($this->created_at) && strtotime($this->created_at) > 0) {
            $this->created_at    = date('Y-m-d', strtotime($this->created_at));
            $where['created_at'] = [[$this->created_at . ' 00:00:00', $this->created_at . ' 23:59:59'], 'between'];
        }
        /**
         * 订单创建时间检索
         */
        if ($this->checkField($this->start_created_at) && $this->checkField($this->end_created_at)) {
            $where['created_at'] = [[$this->start_created_at, $this->end_created_at], 'between'];
        } elseif ($this->checkField($this->start_created_at)) {
            $where['created_at'] = [$this->start_created_at, '>='];
        } elseif ($this->checkField($this->end_created_at)) {
            $where['created_at'] = [$this->end_created_at, '<='];
        }

        $model = ProductModel::makeQueryModel($where, [], $this->getPagination());
        $model->order('id', 'DESC');

        $modelResult = $model->all();

        $list = [];
        foreach ($modelResult as $v) {
            $item   = [
                'id'          => $v->id,
                'goods_name'  => $v->goods_name,
                'goods_img'   => $v->goods_img,
                'goods_price' => $v->goods_price,
                'goods_url'   => $v->goods_url,
                'created_at'  => $v->created_at,
            ];
            $list[] = $item;
        }

        $total                     = $model->lastQueryResult()->getTotalCount();
        $pagination                = $this->getPagination();
        $pagination['total_count'] = $total;

        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        return $result;
    }
}
